const express = require('express');
const app = express();
app.use(require('cors')()) //设置允许跨域
app.use(express.json())
//初始化 mongodb
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/tset',
  //  {
  //   useNewUrlParser: true,
  //   useFindAndModify: true,
  //   useCreateIndex: true,
  // }
)
const Article = mongoose.model('Article', new mongoose.Schema({
  title: {
    type: 'string'
  },
  body: {
    type: 'string'
  }
}));


app.get('/', async (req, res) => {
  res.send("index");
})
//创建文章
app.post("/api/articles", async (req, res) => {
  const article = await Article.create(req.body);
  res.send(article)
})
//查询文章
app.get("/api/articles", async (req, res) => {
  const article = await Article.find();
  res.send(article)
})

//删除文章
app.delete("/api/articles/:id", async (req, res) => {
  await Article.findByIdAndDelete(req.params.id);
  res.send({
    status: true
  })
})
//查询文章
app.get("/api/articles/:id", async (req, res) => {
  const article = await Article.findById(req.params.id);
  res.send(article)
})

//修改文章
app.put("/api/articles/:id", async (req, res) => {
  console.log("id", req.params.id)
  console.log("body", req.body)
  const article = await Article.findByIdAndUpdate(req.params.id, req.body);
  res.send(article)
})

app.listen(3001, function () {
  console.log("http://localhost:3001/#/")
})